﻿/*
 * Created by SharpDevelop.
 * User: khs
 * Date: 2013-09-15
 * Time: 오후 10:45
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace csharp_thread
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		private static Thread t1;
		
		// This delegate enables asynchronous calls for setting
	    // the text property on a TextBox control.
	    delegate void SetTextCallback(string text);
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		void Button1Click(object sender, EventArgs e)
		{
			t1 = new Thread(new ThreadStart(this.thread1));
			t1.Start();
		}
		
		private void thread1(){
			while(true){
				this.SetText(DateTime.Now.ToString());
				Thread.Sleep(100);
			}
		}
		
		// This method demonstrates a pattern for making thread-safe
		// calls on a Windows Forms control. 
		//
		// If the calling thread is different from the thread that
		// created the TextBox control, this method creates a
		// SetTextCallback and calls itself asynchronously using the
		// Invoke method.
		//
		// If the calling thread is the same as the thread that created
		// the TextBox control, the Text property is set directly. 

		private void SetText(string text)
		{
			// InvokeRequired required compares the thread ID of the
			// calling thread to the thread ID of the creating thread.
			// If these threads are different, it returns true.
			if (this.label1.InvokeRequired)
			{	
				SetTextCallback d = new SetTextCallback(SetText);
				this.Invoke(d, new object[] { text });
			}
			else
			{
				this.label1.Text = text;
			}
		}
		
		void Button2Click(object sender, EventArgs e)
		{
			t1.Abort();
		}
		
		
	}
}
